Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

115
Vistas
For event.target in onclick - "Uncaught TypeError TypeError: Cannot set properties of undefined (setting 'value')"

I'm trying to have my html call a javascript function onclick in which the function itself references the event that called it, but I keep getting this error:

Uncaught TypeError TypeError: Cannot set properties of undefined (setting 'value')
    at play (c:\Users\C2Ran\Desktop\Practice\app.js:5:16)
    at onclick (c:\Users\C2Ran\Desktop\Practice\index.html:24:68)

Here's my html:

<!DOCTYPE html>
<head>
    <link rel="stylesheet" href="style.css">
    <script type="text/javascript" src="app.js" defer></script>
</head> 
<body>
    <input type="button" value="X" id="turn" onclick="play(this);">
</body>
</html>

Here's my javascript:

var turn = "X"

function play(event) {
    var cell = event.target;
    cell.value = turn;
    console.log(turn);
    if(turn == "X")
    {
        turn = "O"
    }
    else 
    {
        turn = "X"
    }
}

Is there something I'm missing? Why is it saying value is undefined? Is it not getting the event correctly? Or does onclick not count as an event? I also tried event.currentTarget instead

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Avoid using function calling in HTML attributes, instead use addEventListener,

Your problem is that you are using this when you should be using event.currentTarget

Note: I've improved a bit your code in play() function

function play(cell) {
  cell.value = cell.value === "X" ? "O" : "X"
  console.log(cell.value);
}


document.getElementById('turn').addEventListener('click', e => play(e.currentTarget))
<input type="button" value="X" id="turn">

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda